package com.iss.apartmentmanage.service.impl;

import com.iss.apartmentmanage.entity.Menu;
import com.iss.apartmentmanage.entity.Permission;
import com.iss.apartmentmanage.entity.User;
import com.iss.apartmentmanage.mapper.MenuMapper;
import com.iss.apartmentmanage.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    MenuMapper menuMapper;

    @Autowired
    private  PasswordEncoder passwordEncoder;

    @Override
    //实现系统自带方法loadUserByUsername
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.selectAllUserByUserName(s);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //authorities:存放所有的权限信息
        List<GrantedAuthority> authorities = new ArrayList();
        //根据用户查询用户权限
        List<Permission> permissionList = userMapper.findPermissionByUsername(user.getId());
        for(Permission permission:permissionList){
            GrantedAuthority authority = new SimpleGrantedAuthority(permission.getPerUrl());
            authorities.add(authority);
        }


//        List<Menu> MenuList = menuMapper.selectMenuByUserId(user.getUName());
//
//        for(Menu menu:MenuList){
//            GrantedAuthority authority = new SimpleGrantedAuthority(menu.getMenuCode());
//            authorities.add(authority);
//        }
        UserDetails userDetails= org.springframework.security.core.userdetails.User.withUsername(user.getUName()).password(passwordEncoder.encode(user.getUPwd())).authorities(authorities).build();

        return userDetails;

    }









}
